package com.mio.scalademo

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

import scala.io.StdIn
import java.util.Date

class WorkerActor1(actorRef: ActorRef, name:String) extends Actor {
  var wtime:Date = new Date()
  val masterActorRef: ActorRef = actorRef
  val workName:String = name
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
//      context.system.terminate()
    }
//    case "register" =>{
//      masterActorRef.ath
//      if(masterActorRef.isInstanceOf[MasterActor]){
//      	//s的类型转换为Employee
//      	val s = masterActorRef.asInstanceOf[MasterActor]
//      }
//       masterActorRef.workMap(workName)  = masterActorRef
//    }
    case "updatetime" =>{
      wtime = new Date() 
      println(name + "更新时间" +wtime)
       
    }
    case "sendHeartBeat" => {
      //worker定时发送心跳到master
      println(name +"发送心跳")
      masterActorRef ! "hi" //给 MasterActor 发出消息
    }
  }
}

class MasterActor1() extends Actor {
  var workMap = scala.collection.mutable.Map[String,ActorRef]()
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
//      context.system.terminate()
    }
//     case com.mio.scalademo.WorkerActor(actorRef,name) => {
//      //注册成功
//       workMap("aa") = ActorRef
//      println("注册成功")
//    }
    case "hi" => {
      //更新该 Worker 的最近一次发送心跳的时间
      sender() ! "updatetime"
    }
  }
}

object HeartBeat {
  
    def main(args: Array[String]): Unit = {
      val MyFactory = ActorSystem("myFactory")
      // 创建一个Master
       val masterActorRef = MyFactory.actorOf(Props[MasterActor], "masterActor")
      // 创Worker 并注册到Master
      val workActorRef1: ActorRef = MyFactory.actorOf(Props(new WorkerActor(masterActorRef,"workActor1")), "workActor1")
      val workActorRef2: ActorRef = MyFactory.actorOf(Props(new WorkerActor(masterActorRef,"workActor2")), "workActor2")

       
         while (true) {
           //Worker 定时发送心跳
            workActorRef1 ! "sendHeartBeat"
            workActorRef2 ! "sendHeartBeat"
            // 休眠1000毫秒
            Thread.sleep(1000)
          }
        while (true) {
            //定时检测注册的 Worker 有哪些没有更新心跳，并将其从 hashmap 中删除
            // 休眠2000毫秒
            Thread.sleep(2000)
          }
  }
  
}